package com.spica.spicaschool.ui.replylist

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.rxLifeScope
import com.drakeet.multitype.MultiTypeAdapter
import com.qmuiteam.qmui.widget.pullLayout.QMUIPullLayout
import com.spica.spicaschool.base.BaseFragment
import com.spica.spicaschool.bean.PageEntity
import com.spica.spicaschool.bean.reply.Reply
import com.spica.spicaschool.bean.reply.ReplyRespond
import com.spica.spicaschool.databinding.LayoutListBinding
import com.spica.spicaschool.network.Url
import com.spica.spicaschool.utils.SpUtils
import com.spica.spicaschool.utils.TOKEN_SIGN
import rxhttp.wrapper.param.RxHttp

/**
 * 回复列表
 */
private const val DID_SIGN = "did"

class ReplyListFragment : BaseFragment<LayoutListBinding>() {


    private val items = mutableListOf<Reply>()

    private val page = PageEntity()

    companion object {
        // 传入参数
        fun newInstance(did: String = ""): Fragment {
            val fragment = ReplyListFragment()
            val bundle = Bundle()
            bundle.putString(DID_SIGN, did)
            fragment.arguments = bundle
            return fragment
        }
    }


    override fun setupViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): LayoutListBinding = LayoutListBinding.inflate(inflater,container,false)
    override fun init() {
        // 获取传入类型
        val bundle = arguments
        if (bundle != null) did = bundle.getString(DID_SIGN)
        initData()
    }

    // 适配器
    private lateinit var adapter: MultiTypeAdapter

    // 评论对象的Did
    private var did: String? = null



    // 初始化界面
    private fun initData() {
        // 初始化适配器
        adapter = MultiTypeAdapter()
        // 多类型列表注册多适配器
        adapter.register(ReplyDelegate(requireContext()))
        // 获取数据源
        adapter.items = items
        adapter.setHasStableIds(true) // 做diff
        viewBinding.recycleview.adapter = adapter
        requireActivity()
        onLoadData(true)
        // 下拉刷新设置行为监听
        viewBinding.layoutPull.setActionListener {
            // 延迟刷新动画的关闭
            viewBinding.layoutPull.postDelayed(
                {
                    // 判断用户操作
                    when (it.pullEdge) {
                        // 下拉刷新
                        QMUIPullLayout.PULL_EDGE_TOP -> onLoadData(isRefresh = true)
                        // 到达底部
                        QMUIPullLayout.PULL_EDGE_BOTTOM -> onLoadMore()
                    }
                    viewBinding.layoutPull.finishActionRun(it)
                },
                1000
            )
        }
    }

    /**
     * 加载数据
     * isRefresh：是否刷新
     **/
    @SuppressLint("NotifyDataSetChanged")
    private fun onLoadData(isRefresh: Boolean) {
        if (isRefresh) {
            page.currentPage = 0
        }
        rxLifeScope.launch(
            {
                RxHttp.postForm(Url.COM_LIST)
                    .add("did", did)
                    .add(
                        "token",
                        SpUtils.getSpValue(context = context, key = TOKEN_SIGN, defaultVal = "")
                    )
                    .add("pageNum", ++page.currentPage)
                    .add("pageSize", page.pageSize)
                    .asClass(ReplyRespond::class.java)
                    .subscribe {
                        page.nextPage = it.pageInfo.nextPage
                        loadData(isRefresh, it.data)
                        // 通知UI更新
                        viewBinding.recycleview.post { adapter.notifyDataSetChanged() }
                    }
            },
            {
                Toast.makeText(context, it.message, Toast.LENGTH_SHORT).show()
            }
        )
    }

    // 加载更多
    private fun onLoadMore() {
        if (!page.nextPage) return else
            onLoadData(false)
    }

    // 加载数据
    // isClear：是否清除原数据
    private fun loadData(isClear: Boolean, newData: List<Reply>) {
        if (isClear) items.clear()
        items.addAll(newData)
    }


}
